<?php

namespace App\Service\Collect;


use App\Service\BaiduNlp;
use Illuminate\Support\Facades\Cache;
use QL\QueryList;
use GuzzleHttp\Client;

class Jrj extends Base
{
    // 从金融界采集
    //   采集接口用curl不成功，
    //     QueryList与GuzzleHttp也不成功
    //   只有file_get_contents执行成功

    // 初始化
    protected function init()
    {
        parent::init();
    }


    // 保存到数据表
    public function saveApiDataToDb($_item, $key, $is_file = false)
    {
        $_id     = $_item['iiId'];
        $_title  = $_item['title'];
        $_href   = $_item['infoUrl'];    // 手机链接
        $_href   = $_item['pcInfoUrl'];  // pc端链接
        $_date   = $_item['makeDate'];   // 2023-10-25 09:35:37
        $_author = $_item['paperMediaSource'];
        $_cover  = $_item['picThumb'];
        $_ctime  = strtotime($_date); // 时间
        $_desc   = '';
        $images  = [];

        // 判断链接是否已经采集
        if($is_file){
            $info = $this->isGatherFile($_href);
        } else{
            $info = $this->isGather($_href);
        }
        if($info){
            if(empty($info['sentiment'])){
                $sentiment = $this->baiduNlp($info['text'] ?: $info['description']);
                if($sentiment){
                    if($is_file){
                        $info['sentiment'] = $sentiment;
                        $this->updateFile($_href, $info);
                    } else{
                        $this->updateArticle($info['id'], ['sentiment' => $sentiment]);
                    }
                }
            }

            return $this->return_false(' '.($key + 1).'：==> 已经采集文章：'.$_title);
        }
        // 只采集今天的
        if($_ctime < $this->startTime){
            return $this->return_die(' '.($key + 1).'：==> 文章：不是今天的文章：'.$_title);
        }
        // 如果没有标题
        /*if(empty($_title)){
            return $this->return_false(' '.($key + 1).'：==> 文章：没有标题，不能采集：'.$_title);
        }*/
        // 只采集有评论的
        /*if($_item['comment'] < 1){
            return $this->return_false(' '.($key + 1).'：==> 文章：评论数过少，不采集：'.$_title);
        }*/

        //  主要获取 时间，用户，标题，内容
        //$this->showMsg(' '.($key + 1).'：==> 采集文章：'.$_title);
        try{
            $_ql = QueryList::get($_href);
        } catch(\Exception $e){
            return $this->return_false($e->getMessage());
        }

        $_text = $_ql->find('.main .article .article_content')->text();
        //$_title  = $_ql->find('.main .article .article_title h1')->text();
        //$_time  = $_ql->find('.main .article .article_title .article_info span:eq(0)')->text();
        //$_author  = $_ql->find('.main .article .article_title .article_info i a')->text();

        // 内容与图片
        $rule = ['html' => ['', 'html'], 'text' => ['', 'text'], 'img' => ['img', 'src'],];
        $rule = ['text' => ['', 'text'], 'img' => ['img', 'src'],];
        $list = $_ql->range('.main .article .article_content p')->rules($rule)->queryData();
        foreach($list as $item){
            if($item['img']){
                $images[] = $item['img'];
                if(empty($_cover)){
                    $_cover = $item['img'];
                }
            }
            if(empty($_desc)){
                $_desc = trim($item['text']);
            }
        }
        if(empty($_desc)){
            $_desc = trim($_text);
        }

        // 全匹配 精准匹配
        if((strpos($_desc, $this->keyword) === false) && strpos($_title, $this->keyword) === false){
            return $this->return_false('==> 文章：文章没有精准匹配到搜索的关键字！');
        }
        // 排除关键字 宋正兴
        if(($this->keyword == '董事长宋正') && (strpos($_desc, '宋正兴') !== false) || strpos($_title, '宋正兴') !== false){
            return $this->return_false('==> 文章：文章匹配到其他关键词！');
        }

        // 判断 情感倾向
        //  "sentiment":2,   // 表示情感极性分类结果，0:负向，1:中性，2:正向
        /* $sentiment = '';  // 默认
        $full      = [0 => '负向', 1 => '中性', 2 => '正向'];
        $result    = (new BaiduNlp())->sentiment($_desc);
        if(isset($result['items'][0]['sentiment'])){
            $sentiment = $full[$result['items'][0]['sentiment']] ?? $sentiment;
        } */
        $sentiment = $this->baiduNlp($_desc);


        $_channel  = '';
        $from_site = '金融界';
        $site_id   = 7;
        $_row      = [
            'channel'      => 'article',
            'sentiment'    => $sentiment,
            'link'         => $_href,
            'title'        => trim($_title),
            'description'  => $_desc,
            'text'         => $_desc,
            'time'         => $_ctime,
            'images'       => $images,
            'cover'        => $_cover,
            'author'       => trim($_author),
            'from_channel' => $_channel,
            'from_site'    => $from_site,
            'site_id'      => $site_id,
        ];

        //var_dump($_row);
        if($is_file){
            $res = $this->saveFile($_row);
        } else{
            $res = $this->saveArticle($_row);
        }

        return $res;
    }


    // 获取api接口的列表(测试)
    //   采集接口用curl需要 Cookie
    public function getApiList($keyword, $page = 1, $size = 10)
    {
        if(empty($keyword)){
            return $this->return_die('传递采集关键字！');
        }

        // 使用 curl header
        try{
            $url    = 'https://gateway.jrj.com/jrj-news/news/searchNewsList';
            $post   = $this->makeApiParam($keyword, $page, $size);
            $json   = json_encode($post);
            $header = $this->getHeader();
            $res    = $this->apiCurl()->header($header)->json($json)->request($url);  // ->header($header)
        } catch(\Exception $e){
            return $this->return_false($e->getMessage());
        }


        // 没有cookie的返回数据
        // {"code":50000,"data":{},"msg":"系统异常"}
        $json = json_decode($res, true);
        if(empty($json['code'])){
            return $this->return_die($res);
        }
        if($json['code'] === 50000){
            return $this->return_die($json['msg']);
        }

        return $json['data']['data'];
    }


    // header参数
    protected function getHeader()
    {
        return [
            // 最主要的
            'Content-Type:application/json;charset=UTF-8',
            // 其他
            'Authority:gateway.jrj.com',
            'Method:POST',
            'Path:/jrj-news/news/searchNewsList',
            'Scheme:https',
            'Accept:*/*',
            'Accept-Encoding:gzip,deflate, br',
            'Accept-Language:zh-CN,zh;q=0.9',
            'Origin:https://www.jrj.com.cn',
            'Referer:https://www.jrj.com.cn/',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
        ];
    }


    // 采集地址的参数
    // https://xueqiu.com/query/v1/search/status.json?sortId=1&q=易见股份&count=20&page=1
    protected function makeApiParam($keyword, $page = 1, $size = 10)
    {
        return ["keyWord" => $keyword, "pageSize" => $size, "pageNo" => $page,];
    }

}

